import type { FormProps, FormSchemaInner as FormSchema } from "../types/form";
import { isNumber } from "@/utils/is";
import { useMemo } from "react";

export function useItemLabelWidth(schemaItemRef: FormSchema, propsRef: FormProps) {
	return useMemo(() => {
		const schemaItem = schemaItemRef;
		const { labelCol = {}, wrapperCol = {} } = schemaItem.itemProps || {};
		const { labelWidth, disabledLabelWidth } = schemaItem;

		const { labelWidth: globalLabelWidth, labelCol: globalLabelCol, wrapperCol: globWrapperCol, layout } = propsRef;

		// If labelWidth is set globally, all items setting
		if ((!globalLabelWidth && !labelWidth && !globalLabelCol) || disabledLabelWidth) {
			labelCol.style = {
				textAlign: "left"
			};
			return { labelCol, wrapperCol };
		}
		let width = labelWidth || globalLabelWidth;
		const col = { ...globalLabelCol, ...labelCol };
		const wrapCol = { ...globWrapperCol, ...wrapperCol };

		if (width) width = isNumber(width) ? `${width}px` : width;

		return {
			labelCol: { style: { width }, ...col },
			wrapperCol: {
				style: { width: layout === "vertical" ? "100%" : `calc(100% - ${width})` },
				...wrapCol
			}
		};
	}, [schemaItemRef, propsRef.labelWidth, propsRef.labelCol, propsRef.wrapperCol, propsRef.layout]);
}
